/*
 * $Id: SSHCommand.java,v 1.9 2010/12/21 19:17:23 navdeep_mahajan Exp $
 * 
 * Copyright (C) 2006 General Electric Company. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of the General
 * Electric Company (GE). You shall not disclose this software and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with GE.
 * 
 * GE MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. GE SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING, OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */
package com.ge.healthcare.autosc.common.commands;

import java.io.IOException;
import java.util.List;

import com.ge.healthcare.autosc.common.ASCUtil;
import com.ge.healthcare.autosc.common.dbLogger.StepLogger;
import com.ge.healthcare.autosc.common.exceptions.SSHCommandException;
import com.ge.healthcare.autosc.common.util.ASCIOHandler;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.KBIAuthenticationClient;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.session.SessionChannelClient;
import com.sshtools.j2ssh.transport.IgnoreHostKeyVerification;

/**
 * @author 212042764
 * 
 */
public class SSHCommand {

	private SshClient sshClient = null;
	private SessionChannelClient session = null;

	public SSHCommand() {
		sshClient = new SshClient();
	}

	public void connect(String hostName, String username, String passcode,
			int timeoutMillis) throws SSHCommandException {
		try {
			sshClient.setSocketTimeout(timeoutMillis);
			sshClient.connect(hostName, new IgnoreHostKeyVerification());
			StepLogger.addStepLog("Available connection types for ssh:"
					+ sshClient.getAvailableAuthMethods(username));
			int result = -1;
			List<?> authType = sshClient.getAvailableAuthMethods(username);
			if (!ASCUtil.isNullOrEmptyList(authType)
					&& authType.contains("password")) {
				StepLogger
						.addStepLog("Connecting using password authentication");
				PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
				pwd.setUsername(username);
				pwd.setPassword(passcode);
				// Authenticate the user
				result = sshClient.authenticate(pwd);
			} else {
				StepLogger.addStepLog("Connecting using KBI authentication");
				KBIAuthenticationClient kbi = new KBIAuthenticationClient();
				kbi.setUsername(username);
				ASCKBIRequestHandler kbiHandler = new ASCKBIRequestHandler();
				kbiHandler.setPassCode(passcode);
				kbi.setKBIRequestHandler(kbiHandler);
				// Authenticate the user
				result = sshClient.authenticate(kbi);
			}
			if (result != AuthenticationProtocolState.COMPLETE
					&& !sshClient.isAuthenticated()) {
				throw new SSHCommandException(new StringBuffer(
						"Failed to connect using username:").append(username)
						.append(" and passcode:").append(passcode).toString());
			}
		} catch (IOException ioException) {
			throw new SSHCommandException(new StringBuffer(
					"Failed to connect using username:").append(username)
					.append(" and passcode:").append(passcode).toString(),
					ioException);
		}
	}

	public void disconnect() {
		if (!ASCUtil.isNullOrEmptyObject(sshClient)) {
			sshClient.disconnect();
		}
	}

	public void executeCommand(String command) throws SSHCommandException {
		try {
			// Open ssh channel
			session = sshClient.openSessionChannel();
			if (!session.executeCommand(command)) {
				throw new SSHCommandException("Failed to execute the command:"
						+ command);
			}
		} catch (IOException ioException) {
			throw new SSHCommandException("Failed to execute the command:"
					+ command, ioException);
		}
	}

	public List<String> getResponse() throws SSHCommandException {
		try {
			return ASCIOHandler.readAllAsList(session.getInputStream());
		} catch (IOException ioException) {
			throw new SSHCommandException("Failed to read output. Exception:"
					+ ioException.getMessage(), ioException);
		}
	}
}
